package com.windoent.yugioh.ui.activity.setting;

import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.Button;

import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.baidu.mobstat.StatService;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.registlogin.LoginActivity;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SharedPreUtil;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.utils.some.utilcode.CacheClearUtils;
import com.windoent.yugioh.utils.some.utilcode.util.AppUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.UserModifyInfoItem;
import com.windoent.yugioh.widget.dialog.DeleteSureDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.io.File;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/12 15:08
 * desc   :设置
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private ActivityTitle mActivityTitle;
    private UserModifyInfoItem mItemSafe;
    private UserModifyInfoItem mItemClearCache;
    private UserModifyInfoItem mItemUpdate;
    private UserModifyInfoItem mItemContactUs;
    private Button mBtnLogout;


    @Override
    public int getLayout() {
        return R.layout.activity_setting;
    }

    @Override
    public void initView() {
        super.initView();

        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mItemSafe = (UserModifyInfoItem) findViewById(R.id.item_safe);
        mItemClearCache = (UserModifyInfoItem) findViewById(R.id.item_clear_cache);
        mItemUpdate = (UserModifyInfoItem) findViewById(R.id.item_update);
        mItemContactUs = (UserModifyInfoItem) findViewById(R.id.item_contact_us);
        mBtnLogout = (Button) findViewById(R.id.btn_logout);
    }

    @Override
    public void initData() {
        super.initData();
        setCacheSizeData();
        mItemUpdate.setConText(AppUtils.getAppVersionName());
    }

    //设置缓存大小
    private void setCacheSizeData() {
        try {
            String formatSize = CacheClearUtils.getTotalCacheSize(mContext);
            mItemClearCache.setConText(formatSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mItemSafe.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, SettingSafeAccountActivity.class);
                startActivity(intent);
            }
        });
        mItemClearCache.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shouDeleteCacheDialog();
            }
        });
        mItemUpdate.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 修改
                showUpdateApp(2, AppUtils.getAppVersionName(), getString(R.string.app_update), testUpdateApkUrl, false);
            }
        });
        mItemContactUs.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //联系我们
                startActivity(new Intent(mContext, ContactUsActivity.class));
            }
        });
        mBtnLogout.setOnClickListener(this);
    }

    private DownloadManager downloadManager;
    private String testUpdateApkUrl = "https://imtt.dd.qq.com/16891/apk/4A48D5D5DDA3CEC04A17535B14E4ADDF.apk";

    //应用更新
    private void showUpdateApp(int versionCodeNet, String versionNameNet, String desc, String url, boolean forceUpgrade) {
        UpdateConfiguration configuration = new UpdateConfiguration()
                //输出错误日志
                .setEnableLog(true)
                //设置自定义的下载
                //.setHttpManager()
                //下载完成自动跳动安装页面
                .setJumpInstallPage(true)
                //设置对话框背景图片 (图片规范参照demo中的示例图)
//                .setDialogImage(R.drawable.ic_dialog)
                //设置按钮的颜色
//                .setDialogButtonColor(Color.parseColor("#E743DA"))
                //设置对话框强制更新时进度条和文字的颜色
                //.setDialogProgressBarColor(Color.parseColor("#E743DA"))
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置是否提示后台下载toast
                .setShowBgdToast(false)
                //设置强制更新
                .setForcedUpgrade(forceUpgrade)
                //设置对话框按钮的点击监听
                .setButtonClickListener(new OnButtonClickListener() {
                    @Override
                    public void onButtonClick(int id) {
                        switch (id) {
                            case OnButtonClickListener.CANCEL:
                            case OnButtonClickListener.UPDATE:
                                break;
                        }
                    }
                })
                //设置下载过程的监听
                .setOnDownloadListener(new OnDownloadListener() {
                    @Override
                    public void start() {

                    }

                    @Override
                    public void downloading(int max, int progress) {

                    }

                    @Override
                    public void done(File apk) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void error(Exception e) {

                    }
                });

        downloadManager = DownloadManager.getInstance(this);
        downloadManager.setApkName("YingDieGameKing.apk")
                .setApkUrl(url)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
                .setApkVersionCode(versionCodeNet)
                .setApkVersionName(versionNameNet)
//                .setApkSize("10")
//                .setAuthorities(getPackageName() + ".provider")2.9.0内置
                .setApkDescription(desc)
                .download();
    }

    //清除缓存确认框
    private void shouDeleteCacheDialog() {
        DeleteSureDialog dialog = new DeleteSureDialog(mContext);
        dialog.setTvContent(getString(R.string.string_clear_cache) + mItemClearCache.getTvContent());
        dialog.setYesOnclickListener(new DeleteSureDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                CacheClearUtils.clearAllCache(mContext);
                setCacheSizeData();
            }
        });
        dialog.show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_logout) {//退出登录
            showLogoutDialog();
        }
    }

    //确认dialog
    private void showLogoutDialog() {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_sure_exit));
        dialog.setYesStr(getString(R.string.string_sure));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                exit();
            }
        });
        dialog.show();
    }

    //退出登录
    private void exit() {
        showLoadingDialog("");
        PhoneLive.exitUserAccount(getUserToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean generalBean = gson.fromJson(response, GeneralBean.class);
                            ToastUtils.showText(generalBean.getMsg());
                            SharedPreUtil.put(mContext, Constants.APPTOKEN, "");
                            SharedPreUtil.put(mContext, Constants.USERID, 0);
                            MyApplication.getInstance().cleanLoginInfo();
                            MyApplication.getInstance().cleanMsgNumber();
                            startActivity(new Intent(mContext, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "设置主界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "设置主界面");
    }
}
